package com.cloudptt.api.comm;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.upload.ZipListener;
import com.mcptt.config.body.info.mcdata.FileMataInfo;
import com.mcptt.db.model.SessionInfo;

import android.graphics.Bitmap;
import android.os.Environment;

public class FileOperation {

	private static final String THIS_FILE = "FileOperation";
	public static void deletExcessFile(File dir)
	{
		Log.d(THIS_FILE, "deletExcessFile dir = " + dir.toString());
		File[] fileArr = dir.listFiles( new FilenameFilter(){
			@Override
			public boolean accept(File dir,String fname){ 
				return !fname.contains( "-" );
			}
		});
		if(fileArr == null
				|| fileArr.length <= 10)
		{
			return;
		}
		Log.d( THIS_FILE, "listFiles: " + fileArr.toString( ) );
		Arrays.sort(fileArr, new Comparator<File>() {
			public int compare(File f1, File f2) {
				long diff = f1.lastModified() - f2.lastModified();
				if (diff > 0)
					return 1;
				else if (diff == 0)
					return 0;
				else
					return -1;
			}
			public boolean equals(Object obj) {
				return true;
			}
		});
		
		for(int i = 0; i < fileArr.length - 10; i ++)
		{
			File file = fileArr[i];
			Log.d(THIS_FILE, "deletExcessFile file = " + file.toString());
			boolean isSuc = file.delete();
			Log.d(THIS_FILE, "deletExcessFile result = " + isSuc);
		}
	}
	
	public static int KeyType_None = 0;
	public static int KeyType_Start = 1;
	public static int KeyType_End = 2;
	
	public static void deletAllFile(File dir,int keyType,String key)
	{
		Log.d(THIS_FILE, "deletAllFile dir = " + dir + " keyType = " + keyType + " key = " + key);
		if (dir == null
        		|| dir.exists() == false) 
        { 
			Log.d(THIS_FILE, "deletAllFile !dir.exists()");
            return; 
        } 

        if (!dir.isDirectory()) 
        { 
        	Log.d(THIS_FILE, "deletAllFile !dir.isDirectory()");
        	return;
        }
		File[] fileArr = dir.listFiles();
		if(fileArr == null
				|| fileArr.length <= 0)
		{
			Log.d(THIS_FILE, "deletAllFile fileArr.length <= 0");
			return;
		}
		for(int i = 0; i< fileArr.length; i ++)
		{
			File file = fileArr[i];
			String name = file.getName();
			if(keyType == KeyType_None)
			{
				Log.d(THIS_FILE, "deletAllFile file = " + file);
				file.delete();
			}
			else if(keyType == KeyType_Start
					&& name.startsWith(key))
			{
				Log.d(THIS_FILE, "deletAllFile file = " + file);
				file.delete();
			}
			else if(keyType == KeyType_End
					&& name.endsWith(key))
			{
				Log.d(THIS_FILE, "deletAllFile file = " + file);
				file.delete();
			}
		}
	}
	public static void saveInputStreamToFile(InputStream inputStream, File file) {
		// 创建文件输出流
		try {
			try (FileOutputStream outputStream = new FileOutputStream(file)) {
				int read;
				byte[] buffer = new byte[1024];
				// 从输入流读取数据到缓冲区，并将缓冲区数据写入输出流
				while ((read = inputStream.read(buffer))!= -1) {
					outputStream.write(buffer, 0, read);
				}
			}
		}catch (Exception e)
		{
			Log.d(THIS_FILE, "saveInputStreamToFile e = " + e);
		}
	}
	
	public static void saveImgFile(File file,Bitmap bitmap) 
	{
		FileOutputStream b = null;
		try {
            b = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                b.flush();
                b.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}
	
	private static final String Sms_File_Path = Environment.getExternalStorageDirectory() + File.separator + "CloudPTT" + File.separator + "SMS" + File.separator;// + "REC" + File.separator;
	public static String getVersionPath()
	{
		return Environment.getExternalStorageDirectory() + File.separator + "CloudPTT" + File.separator;
	}

	public static String getFilePath(int type)
	{
		String typeStr = getFileTypeStr(type);
		String path = Sms_File_Path + Common.getDate() + File.separator + typeStr + File.separator;
		return path;

	}
	public static String getFileTypeStr(int type)
	{
		if(type == SessionInfo.Filetype_Pic)
		{
			return "IMG";
		}
		else if(type == SessionInfo.Filetype_Voice)
		{
			return "VOICE";
		}
		else if(type == SessionInfo.Filetype_Video)
		{
			return "VOICE";
		}
		else//(type == SessionInfo.Filetype_File)
		{
			return "FILE";
		}
	}
//	public static void DeleteFilePath(File file) 
//    { 
//		Log.d(THIS_FILE, "DeleteFilePath file = " + file);
//        if (file == null
//        		|| file.exists() == false) 
//        { 
//            return; 
//        } 
//
//        if (file.isDirectory()) 
//        { 
//            File[] childFile = file.listFiles(); 
//            if (childFile == null || childFile.length == 0) 
//            { 
//                return; 
//            } 
//            for (File f : childFile) 
//            { 
//                DeleteFile(f); 
//            } 
//        } 
//    } 
//    private static void DeleteFile(File file) 
//    { 
//    	Log.d(THIS_FILE, "DeleteFile file = " + file);
//        if (file == null
//        		|| file.exists() == false) 
//        { 
//            return; 
//        } 
//        if (file.isFile()
//        		&& file.toString().endsWith(".apk")) 
//        { 
//            file.delete(); 
//            return; 
//        } 
//    }

	/**
	 * 判断文件是否为图片<br>
	 * <br>
	 * @param pInput 文件名<br>
	 * @param pImgeFlag 判断具体文件类型<br>
	 * @return 检查后的结果<br>
	 * @throws Exception
	 */
	public static boolean isPicture(String pInput)
	{
		Log.i(THIS_FILE, "isPicture  pInput = " + pInput);
		// 文件名称为空的场合
//		if(pInput != null
//				&& pInput.length() <= 0){
//			// 返回不和合法
//			return false;
//		}
//
//		int index = pInput.lastIndexOf(".");
//		if(index <= 0)
//		{
//			return false;
//		}
//		// 获得文件后缀名
//		String tmpName = pInput.substring(index + 1,
//				pInput.length());
//		Log.i(THIS_FILE, "isPicture  tmpName = " + tmpName);
		// 声明图片后缀名数组
		String imgeArray [][] = {
				{"bmp", "0"}, {"dib", "1"}, {"gif", "2"},
				{"jfif", "3"}, {"jpe", "4"}, {"jpeg", "5"},
				{"jpg", "6"}, {"png", "7"} ,{"tif", "8"},
				{"tiff", "9"}, {"ico", "10"}
		};
		// 遍历名称数组
		for(int i = 0; i<imgeArray.length;i++){
			// 判断单个类型文件的场合
			Log.i(THIS_FILE, "isPicture  imgeArray [i][0] = " + imgeArray [i][0] + " tmpName.toLowerCase() = " + pInput.toLowerCase());
			if(pInput.toLowerCase().contains(imgeArray [i][0])){
				Log.i(THIS_FILE, "isPicture  return true");
				return true;
			}
		}
		return false;
	}

	public static boolean isAudio(String pInput)
	{
		Log.i(THIS_FILE, "isAudio  pInput = " + pInput);
		// 文件名称为空的场合
//		if(pInput != null
//				&& pInput.length() <= 0){
//			// 返回不和合法
//			return false;
//		}
//
//		int index = pInput.lastIndexOf(".");
//		if(index <= 0)
//		{
//			return false;
//		}
//		// 获得文件后缀名
//		String tmpName = pInput.substring(index + 1,
//				pInput.length());
//		Log.i(THIS_FILE, "isAudio  tmpName = " + tmpName);
		// 声明图片后缀名数组
		String array [][] = {
				{"amr", "0"}, {"mp3", "1"}, {"wma", "2"}
		};
		// 遍历名称数组
		for(int i = 0; i<array.length;i++){
			// 判断单个类型文件的场合
			if(pInput.toLowerCase().contains(array [i][0])){
				Log.i(THIS_FILE, "isAudio  return true");
				return true;
			}
		}
		return false;
	}

	public static String getFileExtension(String fileName) {
		if (fileName == null || fileName.isEmpty()) {
			return "";
		}
		int lastIndexOfDot = fileName.lastIndexOf(".");
		if (lastIndexOfDot == -1 || lastIndexOfDot == 0 || lastIndexOfDot == fileName.length() - 1) {
			return "";
		} else {
			return fileName.substring(lastIndexOfDot + 1).toLowerCase();
		}
	}

//	public static String abbreviateFileName(String fileName, int length) {
//		if (fileName == null || fileName.length() <= length) {
//			return fileName;
//		}
//		return fileName.substring(0, length);
//	}
public static String abbreviateFileName(String fileName, int length) {
	if (fileName == null || fileName.length() <= length) {
		return fileName;
	}

	int dotIndex = fileName.lastIndexOf('.');
	if (dotIndex == -1) {
		return fileName.substring(0, length);
	}

	String namePart = fileName.substring(0, dotIndex);
	String extensionPart = fileName.substring(dotIndex);

	if (namePart.length() + extensionPart.length() <= length) {
		return fileName;
	}

	int nameLength = length - extensionPart.length() - 3; // 3 为省略号的长度
	if (nameLength <= 0) {
		return fileName.substring(0, length);
	}

	return namePart.substring(0, nameLength) + "..." + extensionPart;
}
	public static String getReadableFileSize(String sizeVal) {
		Log.debug(FileOperation.class, "getReadableFileSize sizeVal = " + sizeVal);
		float size = CheckData.parseFloat(sizeVal);
		Log.debug(FileOperation.class, "getReadableFileSize size = " + size);
		if (size <= 0) return "0 B";
		final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
		int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
		return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
	}


	/**
	 * 压缩文件和文件夹
	 *
	 * @param srcFileString 要压缩的文件或文件夹
	 * @param zipFileString 压缩完成的Zip路径
	 * @throws Exception
	 */

	private int fileCount = 0;
	private int fileIndex = 0;
	public void zipFolder(String srcFileString, String zipFileString, ZipListener listener) throws Exception
	{
//创建ZIP
		ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));
//创建文件
		File file = new File(srcFileString);
//压缩
		Log.debug(FileOperation.class,"ZipFolder file.getParent = "+file.getParent()+"file.getAbsolutePath = "+file.getAbsolutePath());
		zipFiles(file.getParent()+ File.separator, file.getName(), outZip,listener);
//完成和关闭
		outZip.finish();
		outZip.close();
	}

	/**
	 * 压缩文件
	 *
	 * @param folderString
	 * @param fileString
	 * @param zipOutputSteam
	 * @throws Exception
	 */

	private void zipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam,ZipListener listener) throws Exception
	{
		Log.debug(FileOperation.class,"ZipFiles folderString = "+folderString +"fileString = " + fileString);
		if (zipOutputSteam == null)
		{
			return;
		}
		File file = new File(folderString + fileString);
		if (file.isFile())
		{
			fileIndex ++;
			if(listener != null)
			{
				listener.onProcess(fileIndex,fileCount);
			}
			ZipEntry zipEntry = new ZipEntry(fileString);
			FileInputStream inputStream = new FileInputStream(file);
			zipOutputSteam.putNextEntry(zipEntry);
			int len;
			byte[] buffer = new byte[4096];
			while ((len = inputStream.read(buffer)) != -1)
			{
				zipOutputSteam.write(buffer, 0, len);
			}
			zipOutputSteam.closeEntry();
		}
		else
		{
//文件夹
			String fileList[] = file.list();
			fileCount = fileList.length;
			if(listener != null)
			{
				listener.onProcess(fileIndex,fileCount);
			}
//没有子文件和压缩
			if (fileList.length <= 0) {
				ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
				zipOutputSteam.putNextEntry(zipEntry);
				zipOutputSteam.closeEntry();
			}
//子文件和递归
			for (int i = 0; i < fileList.length; i++)
			{
				zipFiles(folderString+fileString+"/", fileList[i], zipOutputSteam,listener);
			}
		}
	}

	public static File getDefaultName(int type,String dir) throws IOException
	{
		String typeStr = getFilePath(type);
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		String imageFileName = typeStr + timeStamp + "_";
		File storageDir = new File(dir);
		return File.createTempFile(imageFileName, ".jpg", storageDir);
	}
}
